package linkFinder;
import java.util.Comparator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;

/**
 * Creates link comparator that's compare string according to
 * url itself and querystring (after symbol ?). Comparing as regular Strings. Only
 * differennce is that strings are equal when one query parameter has different value.
 * (if strings are equal, so them are equal as regular string)  
 * @author Grinfeld Igor, ....
 *
 */
public class LinkComparator implements Comparator {

	public int compare(Object arg0, Object arg1) {
		return ( arg0 instanceof String && arg1 instanceof String 
					? compareStr((String)arg0, (String)arg1) : -1
				);
	}
	
	public int compareStr(String arg0, String arg1) {
		return ( isLinkedEquals(arg0, arg1) ? 0 : arg0.compareToIgnoreCase(arg1) );
	}
	
	protected boolean isLinkedEquals(String str1, String str2){
		boolean isYetEquals = true;
		String url1 = (str1.indexOf('?') != -1 ? str1.substring(0, str1.indexOf('?')) : str1);
		String url2 = (str2.indexOf('?') != -1 ? str2.substring(0, str2.indexOf('?')) : str2);
		if(!url1.equals(url2)){
			return false;
		}
		boolean flag = true;
		// it equals when all parameter names are the same
		// and only (one value is different)
		// to compare base url before doing this.
		Map<String, String> map = new TreeMap<String, String>();
		StringTokenizer token1 = new StringTokenizer( ( str1.indexOf('?') != -1 ? str1.substring( str1.indexOf('?') +1 ) : "" ),"&");
		StringTokenizer token2 = new StringTokenizer( ( str2.indexOf('?') != -1 ? str2.substring( str2.indexOf('?') +1 ) : "" ),"&");
		
		while(token1.hasMoreTokens()){
			String token = token1.nextToken();
			int ind = token.indexOf('=');
			if(ind != -1){
				String paramName = ( ind != token.length() ? token.substring(0, ind) : token );
				String paramVal = ( ind != token.length() ? token.substring(ind+1) : "" );
				map.put(paramName, paramVal);
			}else{
				isYetEquals = false;
			}
		}
		
		if(isYetEquals){
			int counter1 = 0;
			int counter2 = 0;
			
			while(counter1 == 0 && counter2 <= 1 && token2.hasMoreTokens()){
				String token = token2.nextToken();
				int ind = token.indexOf('=');
				String paramName = ( ind != token.length() ? token.substring(0, ind) : token );
				String paramVal = ( ind != token.length() ? token.substring(ind+1) : "" );
				if(map.containsKey(paramName)){
					String checkVal = map.get(paramName);
					if(!paramVal.equals(checkVal)){
						counter2++;
					}
				}else{
					counter1++;
				}
			}
			
			if(counter1 != 0 || counter2 > 1){
				flag = false;
			}
		}
		return flag && isYetEquals;
	}

}
